package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.service.ApArticleRelationService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.service.ApUnLikeBehaviorService;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApArticleRelationServiceImpl implements ApArticleRelationService {
    @Autowired
    ApLikesBehaviorService apLikesBehaviorService;
    @Autowired
    ApUnLikeBehaviorService apUnLikeBehaviorService;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    /**
     * 查询用户文章的点赞\不喜欢
     * @param dto
     * @return
     */
    @Override
    public Map findApArticleRelation(ApArticleRelationDto dto) {
        // 预封装结果
        Map<String, Object> map = new HashMap<>();
        map.put("islike",false);
        map.put("isunlike",false);
        // 参数校验
        if (dto==null||dto.getArticleId()==null||dto.getEntryId()==null){
            return map;
        }
        /**
         * 实体类型
         *  0 终端设备
         *  1 用户
         */
        // 查询行为实体
        ApBehaviorEntry behaviorEntry = null;
        if (dto.getType()==1){
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getEntryId(), null);
        }else {
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEntryId());
        }
        if (behaviorEntry==null){
            return map;
        }
        // 行为实体ID
        map.put("entryId",behaviorEntry.getId());
        // 查询文章点赞
        ApLikesBehavior apLikesBehavior = apLikesBehaviorService.getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApLikesBehavior::getEntryId, behaviorEntry.getId()));
        if (apLikesBehavior!=null && apLikesBehavior.getOperation()==0){
           map.put("islike",true);
        }
        // 查询文章不喜欢behaviorEntry
        ApUnlikesBehavior apUnlikesBehavior = apUnLikeBehaviorService.getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, behaviorEntry.getId()));
        if (apUnlikesBehavior!=null&&apUnlikesBehavior.getType()==0){
            map.put("isunlike",true);
        }
        //返回结果
        return map;
    }
}
